package org.fog.json.map;

import org.fog.json.common.JsonCC;
import org.fog.json.common.JsonMapReaderType;
import org.fog.json.exception.JsonCCException;
import org.fog.json.io.JsonMapReader;
import org.fog.json.io.JsonMapReaderImp;
import org.fog.tools.IOKit;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 * User: 缪凯
 * Date: 12-2-3
 * Time: 下午4:29
 */
public class JsonMapCubeImp implements JsonMapCube {
    private static JsonMapCubeImp CUBE = null;
    private JsonCC cc = null;
    private ConcurrentHashMap<String , JsonMapPackage> packages = null;

    //私有构造方法
    private JsonMapCubeImp(JsonCC cc) throws IOException {
        //配置文件赋值
        this.cc = cc;
        //创建cube的第一层“包”
        this.packages = new ConcurrentHashMap<String , JsonMapPackage>();
        //制造cube
        this.makeCube();
    }

    /**
     * @param cc  配置bean
     * @return  返回cube实例
     * @throws JsonCCException
     * @throws IOException
     */
    public static JsonMapCube initJsonMapCube(JsonCC cc) throws JsonCCException, IOException {
        if(cc == null)
            throw new JsonCCException();
        if(JsonMapCubeImp.CUBE == null)
            JsonMapCubeImp.CUBE = new JsonMapCubeImp(cc);
        return JsonMapCubeImp.CUBE;
    }

    private void makeCube() throws IOException {
        List<URI> paths = this.cc.getJsonMapPaths();
        IOKit kit = IOKit.getDefaultIOKit();
        JsonMapReader reader;
        for(URI path : paths){
            //获取path路径下的所有xml配置文件
            List<File> files = kit.listFiles(path , ".*\\.xml");
            for(File file : files){
                reader = new JsonMapReaderImp(file);
                if(reader.makeReady() == JsonMapReaderType.Ready)
                    reader.readPackage().setCube(this);
                    this.packages.put(reader.readPackage().getName() , reader.readPackage());
            }
        }
    }

    public Map<String, JsonMapPackage> getPackages() {
        return this.packages;
    }

    public JsonMapPackage getPackage(String jsonPackage) {
        if(jsonPackage != null && !"".equals(jsonPackage) && this.packages != null)
            return  this.packages.get(jsonPackage);
        return null;
    }

    public Map<String, JsonMapBody> getBodies(String jsonPackage) {
        if(jsonPackage != null && !"".equals(jsonPackage) && this.packages != null)
            return  this.packages.get(jsonPackage).getBodies();
        return null;
    }

    public JsonMapBody getBody(String jsonPackage, String jsonId) {
        if(jsonPackage != null && jsonId != null
                && !"".equals(jsonPackage) && !"".equals(jsonId)
                && this.packages != null)
            return this.packages.get(jsonPackage).getBody(jsonId);
        return null;
    }
}
